package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbDictMapper;
import com.bwie.mapper.TbProdImageMapper;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbDict;
import com.bwie.pojo.TbProd;
import com.bwie.pojo.TbProdImage;
import com.bwie.service.TbProdService;
import com.bwie.mapper.TbProdMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
* @author 28242
* @description 针对表【tb_prod】的数据库操作Service实现
* @createDate 2025-04-24 19:37:49
*/
@Service
public class TbProdServiceImpl extends ServiceImpl<TbProdMapper, TbProd>
    implements TbProdService{

    @Autowired
    TbProdMapper tbProdMapper;

    @Autowired
    TbDictMapper tbDictMapper;


    @Autowired
    TbProdImageMapper tbProdImageMapper;

    @Autowired
    HttpServletRequest request;


    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    public R getprodList(PageInfoVo pageInfoVo) {


        Page<TbProd> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        Page<TbProd> tbProdPage = tbProdMapper.getProdlist(page,pageInfoVo.getKeyWord());

        List<TbProd> records = tbProdPage.getRecords();
        for (TbProd record : records) {
            List<TbProdImage> list = tbProdImageMapper.selectList(new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId, record.getProdId()));

            record.setTbProdImages(list);
        }
        for (TbProd record : tbProdPage.getRecords()) {
            record.setBuyNum(1);
        }



        return R.OK(tbProdPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addProd(TbProd tbProd) {
        String token = request.getHeader("token");

        if (token==null){
            return R.ERROR(404,"用户没有登录");
        }
        Integer userId = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userId", Integer.class);


        QueryWrapper<TbProd> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbProd::getProdName,tbProd.getProdName());
        TbProd tbProd1 = tbProdMapper.selectOne(wrapper);
        if (tbProd1!=null){
            return R.ERROR(404,"商品重复");
        }
        tbProd.setProdType(0);
        tbProd.setCreateTime(new Date());

        tbProd.setUserId(userId);

        tbProdMapper.insert(tbProd);


        if (tbProd.getTbProdImages()!=null && tbProd.getTbProdImages().size()>0){
            for (TbProdImage tbProdImage : tbProd.getTbProdImages()) {
                tbProdImage.setProdId(tbProd.getProdId());
                tbProdImageMapper.insert(tbProdImage);
            }
        }


        return R.OK();
    }

    @Override
    public R getDictList(Integer typeId) {

        List<TbDict> tbDicts = tbDictMapper.selectList(new QueryWrapper<TbDict>().lambda().eq(TbDict::getDictType, typeId));




        return R.OK(tbDicts);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteById(Integer prodId) {

        //删除商品图片
        tbProdImageMapper.delete(new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId,prodId));

        //删商品
        tbProdMapper.deleteById(prodId);

        return R.OK();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateprodById(TbProd tbProd) {

        TbProd prod = tbProdMapper.selectById(tbProd.getProdId());
        if (prod==null){
            return R.ERROR(404,"该商品不存在");
        }
        tbProdMapper.updateById(tbProd);

        tbProdImageMapper.delete(new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId,tbProd.getProdId()));


        if (tbProd.getTbProdImages()!=null && tbProd.getTbProdImages().size()>0){
            for (TbProdImage tbProdImage : tbProd.getTbProdImages()) {
                tbProdImage.setProdId(tbProd.getProdId());
                tbProdImageMapper.insert(tbProdImage);
            }
        }

        return R.OK();
    }

    @Override
    public R sendMessage(String msg) {

        System.out.println("KafaKa发送消息:"+msg);
        kafkaTemplate.send("topic-text",msg);

        return R.OK();
    }

    @Override
    public R changeProdStatus(TbProd tbProd) {
        TbProd prod = tbProdMapper.selectById(tbProd);
        if (prod==null){
            return R.ERROR(404,"商品不存在");
        }
        //审核
        if (tbProd.getProdStatus()==1){
            prod.setProdStatus(tbProd.getProdStatus());
            tbProdMapper.updateById(prod);
        }
        //上线(审核通过) ==2
        if (tbProd.getProdStatus()==2){
            prod.setProdStatus(tbProd.getProdStatus());
            tbProdMapper.updateById(prod);

            //发短信
            String message = JSON.toJSONString(prod);
            kafkaTemplate.send("topic-shop",message);
            System.out.println("发送kafuka消息");

        }
        //驳回
        if (tbProd.getProdStatus()==3){
            if (StringUtils.isEmpty(tbProd.getReason())){
                return R.ERROR(500,"审核驳回必须填写理由");
            }
            prod.setProdStatus(tbProd.getProdStatus());
            prod.setReason(tbProd.getReason());
            tbProdMapper.updateById(prod);

            //发邮箱
            String message = JSON.toJSONString(prod);
            kafkaTemplate.send("topic-shop",message);
            System.out.println("发送kafuka消息");
        }

        //下线
        if (tbProd.getProdStatus()==4){
            prod.setProdStatus(tbProd.getProdStatus());
            tbProdMapper.updateById(prod);
        }


        return R.OK();
    }

    @KafkaListener(topics = "topic-text")
    public void recvTestMessage(String msg, Acknowledgment acknowledgment){

        System.out.println("KaFAKa接受到消息:"+msg);

        acknowledgment.acknowledge();

    }
}




